package com.wondertek.service.service.sys.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wondertek.service.dto.sys.req.AppVersionAddReq;
import com.wondertek.service.dto.sys.req.AppVersionQueryReq;
import com.wondertek.service.dto.sys.req.AppVersionUpdateReq;
import com.wondertek.service.entity.sys.AppVersionPo;
import com.wondertek.service.mapper.sys.AppVersionMapper;
import com.wondertek.service.service.sys.IAppVersionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author wangyu
 */
@Service
@Slf4j
public class AppVersionServiceImpl extends ServiceImpl<AppVersionMapper, AppVersionPo> implements IAppVersionService {

    @Override
    public Page<AppVersionPo> page(AppVersionQueryReq appVersionQueryReq) {
        LambdaQueryWrapper<AppVersionPo> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(appVersionQueryReq.getVersion())) {
            wrapper.like(AppVersionPo::getVersion, appVersionQueryReq.getVersion());
        }
        wrapper.orderByDesc(AppVersionPo::getReleaseDate);
        return this.page(new Page<>(appVersionQueryReq.getPageNo(), appVersionQueryReq.getPageSize()), wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(AppVersionAddReq appVersionAddReq) {
        AppVersionPo appVersionPo = new AppVersionPo();
        BeanUtil.copyProperties(appVersionAddReq, appVersionPo);
        this.save(appVersionPo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AppVersionUpdateReq appVersionUpdateReq) {
        AppVersionPo appVersionPo = new AppVersionPo();
        BeanUtil.copyProperties(appVersionUpdateReq, appVersionPo);
        appVersionPo.setReleaseDate(new Date());
        this.updateById(appVersionPo);
    }

    @Override
    public AppVersionPo getAppVersion(String version, Integer type) {
        AppVersionPo appVersionPo = this.lambdaQuery().eq(AppVersionPo::getAppType, type).orderByDesc(AppVersionPo::getReleaseDate).last("limit 1").one();
        appVersionPo.setStatus(0);
        if (ObjectUtil.isEmpty(appVersionPo)) {
            return appVersionPo;
        }
        if (!StrUtil.equals(version, appVersionPo.getVersion())) {
            appVersionPo.setStatus(1);
        }
        return appVersionPo;
    }
}
